package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.swing.text.StyleConstants;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    @Override
    @Transactional
    public long addTask(Task task) {
        //添加任务到数据库中
        boolean success=addTaskToDB(task);
        if (success){
            //添加任务到redis中
            addTaskToRedis(task);

        }

        return task.getTaskId();
    }

    /**
     * 删除任务
     * @param taskId
     * @return
     */
    @Override
    @Transactional
    public boolean deleteTask(long taskId) {

        Task task=null;
        try{
            //删除数据库中的任务
            int i = taskinfoMapper.deleteById(taskId);
            //修改任务日志为2
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(2);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE,5);
            long timeInMillis = calendar.getTimeInMillis();
            String key=task.getTaskType()+"_"+task.getPriority();
            //删除redis中的任务

                //删除list里面的元素
                System.out.println("删除list的元素");
                Long l1 = cacheService.lRemove("topic_" + key, 0, JSON.toJSONString(task));
                System.out.println("删除list的元素返回:"+l1);

                System.out.println("删除zet的元素");
                Long l2 = cacheService.zRemove("future_" + key, JSON.toJSONString(task));
                System.out.println("删除zet的元素返回:"+l2);

        }catch (Exception e){
            e.printStackTrace();
            log.error("taskId:{},删除失败",taskId);
            return false;
        }

        return true;
    }

    /**
     * 根据优先级和类型拉取任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Taskinfo poll(int type, int priority) {

        Taskinfo taskinfo=null;
        try{
            String key=type+"_"+priority;
            String result = cacheService.lRightPop("topic_" + key);
            taskinfo = JSONObject.parseObject(result, Taskinfo.class);
            if (taskinfo!=null){
                int i = taskinfoMapper.deleteById(taskinfo.getTaskId());
                TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskinfo.getTaskId());
                taskinfoLogs.setStatus(1);
                taskinfoLogsMapper.updateById(taskinfoLogs);
            }

        }catch (Exception e){
            log.error("拉取任务失败");
            e.printStackTrace();
        }
        return taskinfo;
    }

    private void addTaskToRedis(Task task) {
        //任务的key
        String key=task.getTaskType()+"_"+task.getPriority();

        //获取五分钟之后的毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long timeInMillis = calendar.getTimeInMillis();

        //如果任务的执行时间小于当前时间，存入到list类型中
        if (task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lLeftPush("topic_"+key, JSON.toJSONString(task));

        }else if (task.getExecuteTime()<timeInMillis){
            //如果任务的执行时间大于当前时间，但是小于预设时间，则存入zset中
            cacheService.zAdd("future_"+key,JSON.toJSONString(task),task.getExecuteTime());

        }


    }

    private boolean addTaskToDB(Task task) {

        boolean flag=true;
        try{
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            task.setTaskId(taskinfo.getTaskId());

            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(task,taskinfoLogs);
            taskinfoLogs.setStatus(0);
            taskinfoLogs.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoLogs.setVersion(1);
            taskinfoLogsMapper.insert(taskinfoLogs);
        }catch (Exception e){
            e.printStackTrace();
            flag=false;
        }

        return flag;
    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 0/5 * * * ? ")
    public void reFresh(){


        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (!StringUtils.isEmpty(token)){
            log.info("开始执行将zset中的数据刷到list中的定时任务");
            //获取所有未来数据的集合key
            Set<String> futureKeys = cacheService.scan("future_" + "*");
            if (futureKeys!=null){
                for (String futureKey : futureKeys) {
                    Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                    String topicKey="topic"+futureKey.split("future")[1];
                    if (tasks!=null){
                        //同步数据
                        cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
                        log.info("数据写入成功,futurekey为:{},topicKey为:{}",futureKey,topicKey);
                    }


                }
            }

        }


    }


    @PostConstruct
    @Scheduled(cron = "0 0/5 * * * ? ")
    public void reloadDataToRedis(){
        //清理缓存中的数据
        log.info("清理缓存中的任务");
        Set<String> futureKeys = cacheService.scan("future_" + "*");
        Set<String> topicKeys = cacheService.scan("topic_" + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);

        //查询小于未来五分钟的时间的任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        List<Taskinfo> taskInfos = taskinfoMapper.selectList(new LambdaQueryWrapper<Taskinfo>()
                .lt(Taskinfo::getExecuteTime, calendar));
        if (taskInfos!=null){
            for (Taskinfo taskInfo : taskInfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskInfo,task);
                task.setExecuteTime(taskInfo.getExecuteTime().getTime());
                //将任务写入到redis中
                addTaskToRedis(task);

            }
        }
        log.info("任务写入redis成功");

    }


}
